package com.zx.dsptuneup_TriMic.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.example.base.tools.tools.StringUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.zx.dsptuneup_TriMic.Base.BaseActivity;
import com.zx.dsptuneup_TriMic.Common.TextDrawable;
import com.zx.dsptuneup_TriMic.R;
import com.zx.dsptuneup_TriMic.Tools.Constant;
import com.zx.dsptuneup_TriMic.Tools.UrlConstant;
import com.zx.dsptuneup_TriMic.Util.ClickUtil;
import com.zx.dsptuneup_TriMic.Util.NetWorkUtils;
import com.zx.dsptuneup_TriMic.Util.ToastUtil;
import com.zx.dsptuneup_TriMic.bean.BasicResponse;
import com.zx.dsptuneup_TriMic.bean.LoginBean;
import com.zx.dsptuneup_TriMic.network.DefaultObserver;
import com.zx.dsptuneup_TriMic.network.NetWorkManager;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.usernameEdt)
    EditText usernameEdt;
    @BindView(R.id.passwordEdt)
    EditText passwordEdt;
    @BindView(R.id.rememberBtn)
    TextDrawable rememberBtn;
    @BindView(R.id.loginBtn)
    Button loginBtn;
    @BindView(R.id.ipconfigTxt)
    TextView ipconfigTxt;
    @BindView(R.id.ipEdt)
    EditText ipEdt;
    @BindView(R.id.loginBtnRel)
    RelativeLayout loginBtnRel;


    private final String TAG = "LoginActivity.class";
    private boolean isShowIP = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);

        isShowIP = false;
        // 设置IP类型输入
        ipEdt.setInputType(InputType.TYPE_CLASS_NUMBER);
        String digits = "0123456789." ;
        ipEdt.setKeyListener(DigitsKeyListener.getInstance(digits));

        hideBottomUIMenu();
        dengluBtn_Action();

////                double f = 0.83079689;
//        double f = -1.77781188488;
//        String str = NumberBaseConversionUtil.tenDecimalToSixTeen(f);
//        Log.e(TAG, "getHexadecimal====="+str);
////si
//        String aa = "8d00";
//        double value = NumberBaseConversionUtil.SixToDecimalTen(aa);
//        Log.e(TAG, "getHexadecimal====="+value);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Hawk.contains(Constant.username)) {
            usernameEdt.setText(Hawk.get(Constant.username));
        }
        if (Hawk.contains(Constant.password)) {
            passwordEdt.setText(Hawk.get(Constant.password));
        }
        if (Hawk.contains(Constant.ipconfig)) {
            ipEdt.setText(Hawk.get(Constant.ipconfig));
        }
    }

    protected void dengluBtn_Action() {
        rememberBtn.setSelected(true);
        rememberBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rememberBtn.setSelected(!rememberBtn.isSelected());
            }
        });

        ipconfigTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int dp15 = ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()));
                int dp65 = ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 65, getResources().getDisplayMetrics()));
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) loginBtnRel.getLayoutParams();
                if (isShowIP) {
                    lp.topMargin = dp15;
                    ipEdt.setVisibility(View.GONE);
                }else {
                    lp.topMargin = dp65;
                    ipEdt.setVisibility(View.VISIBLE);
                }
                isShowIP = !isShowIP;
                loginBtnRel.setLayoutParams(lp);
            }
        });

        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ClickUtil.isFastClick(1000, view)) {
                    return;
                }
                if (StringUtils.isEmpty(usernameEdt.getText())) {
                    ToastUtil.makeText(LoginActivity.this, "请输入账号");
                    return;
                }
                if (StringUtils.isEmpty(passwordEdt.getText())) {
                    ToastUtil.makeText(LoginActivity.this, "请输入密码!");
                    return;
                }
                if (rememberBtn.isSelected()) {
                    Hawk.put(Constant.password, passwordEdt.getText().toString());
                    Hawk.put(Constant.username, usernameEdt.getText().toString());
                }
                if (!StringUtils.isEmpty(ipEdt.getText()) && !StringUtils.checkIsIP(ipEdt.getText().toString())){
                    ToastUtil.makeText(LoginActivity.this, "ip格式不正确!");
                    return;
                }

                mDialog.setMsg("正在连接...");
                showDialog();
                if(!NetWorkUtils.pingHost(ipEdt.getText().toString())){
                    ToastUtil.makeText(LoginActivity.this, "IP不通,请重新配置IP!");
                    mDialog.dismiss();
                    return;
                }

                if (!StringUtils.isEmpty(ipEdt.getText())) {
                    // "http://192.168.31.233:8012"
                    UrlConstant.baseUrl = "http://"+ipEdt.getText().toString() + ":8012";
                    NetWorkManager.getInstance().resetNetworkApi();
                    Hawk.put(Constant.ipconfig, ipEdt.getText().toString());
                }

                HashMap map = new HashMap();
                map.put("username", usernameEdt.getText().toString());
                map.put("password", passwordEdt.getText().toString());
//                Log.d(TAG, "map == " + map);

                loginBtn.setSelected(true);
                NetWorkManager.getInstance().getNetWorkApiService().loginByUserName(map).compose(LoginActivity.this.<BasicResponse<LoginBean>>bindToLifecycle())
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<BasicResponse<LoginBean>>() {
                            @Override
                            protected void onSuccess(BasicResponse<LoginBean> response) {
                                LoginBean loginbean = response.getData();
                                if (response != null) {
                                    closeKeyboardHidden(LoginActivity.this);
                                    Hawk.put(Constant.token, loginbean.getToken());

                                    Intent intent = new Intent(LoginActivity.this, HomeListActivity.class);
                                    startActivity(intent);
                                    finish();
                                }
                            }

                            @Override
                            protected void onFail(BasicResponse<LoginBean> response) {
                                super.onFail(response);
                                mDialog.dismiss();
                            }

                            @Override
                            public void onError(@NonNull Throwable e) {
                                super.onError(e);
                                mDialog.dismiss();
                            }
                        });

            }
        });

    }

    /**
     * 隐藏软键盘
     **/
    private static void closeKeyboardHidden(Activity context) {
        View view = context.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /**
     * 隐藏虚拟按键，并且设置成全屏
     */
    protected void hideBottomUIMenu() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                    | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                    | View.SYSTEM_UI_FLAG_IMMERSIVE;
            decorView.setSystemUiVisibility(uiOptions);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
    }


    @Override
    protected void initImmersionBar() {
        ImmersionBar mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
        mImmersionBar.transparentBar();
    }

}
